package com.cxria.script

class FileUtils{

    static void join2(List<String> filepaths, String outpath){
        def fw = new FileOutputStream(outpath)
        def bos = new BufferedOutputStream(fw)
        filepaths.each { filepath ->
            def fis = new FileInputStream(filepath)
            def bis = new BufferedInputStream(fis)
            def blockSize = 1024 * 10
            def bytes = new byte[blockSize]
            def len
            while ((len = bis.read(bytes, 0, blockSize)) != -1){
                bos.write(bytes)
            }
            bis.close()
            fis.close()
        }
        bos.close()
        fw.close()
    }

    static void join(List<String> filepaths, String outpath){
        def fw = new FileOutputStream(outpath)
        filepaths.each { filepath ->
            def fr = new File(filepath)
            def bytes = fr.getBytes()
            fw.write(bytes)
        }
        fw.close()
    }

    static void append(String filepath, String appendFilepath, long seek){
        def fis = new FileInputStream(appendFilepath)
        append(filepath, fis, seek)
    }

    static void append(String filepath, InputStream appendData, long seek){
        def bis = new BufferedInputStream(appendData)
        def raf = new RandomAccessFile(filepath, 'rw')
        raf.seek(seek)
        def blockSize = 1024 * 10
        def bytes = new byte[blockSize]
        def len
        while ((len = bis.read(bytes, 0, blockSize)) != -1){
            raf.write(bytes, 0, blockSize)
        }
        raf.close()
        bis.close()
        appendData.close()
    }

}